import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

//1.导入组件
import login from '@/views/user/login.vue'
import layout from '@/views/layout.vue/'
import home from '@/views/home/home.vue'
import qa from '@/views/qa/qa.vue'
import movie from '@/views/movie/movie.vue'
import user from '@/views/user/user.vue'
import notfound from '@/views/notfound/notfound.vue'
import edit from '@/views/user/edit.vue'
import article from '@/views/home/article.vue'
import search from '@/views/home/search.vue'
import searchResult from '@/views/home/searchResult.vue'
import student from '@/views/user/student.vue'
//2.路由的规则
const routes = [{
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'edit',
    path: '/edit',
    component: edit
  },
  {
    name: 'myarticle',
    path: '/article',
    component: article
  },
  {
    name: 'search',
    path: '/search',
    component: search
  },
  {
    name: 'searchResult',
    path: '/searchResult',
    component: searchResult
  },
  {
    name: 'student',
    path: '/student',
    component: student
  },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [{
        name: 'home',
        path: '/home',
        component: home
      },
      {
        name: 'qa',
        path: '/qa',
        component: qa
      },
      {
        name: 'movie',
        path: '/movie',
        component: movie
      },
      {
        name: 'user',
        path: '/user',
        component: user,
        //路由元信息
        meta: {
          isLogin: true
        }
      },
      {
        path: '/',
        redirect: 'home'
      }
    ]
  },
  {
    name: 'notfound',
    path: '/notfound',
    component: notfound
  },
  {
    //代表 * 任何路径
    //路由默认从上往下匹配,
    path: '*',
    redirect: '/notfound'
  }
]

const router = new VueRouter({
  routes
})

//路由导航前置守卫,路由导航守卫一定要写在 创建路由对象的  后面
//导入token
import {
  getToken
} from '@/utils/token.js'
router.beforeEach((to, from, next) => {
  //to:目标路由  要跳到哪里
  console.log("", to);
  //from: 来源路由  从哪个路由跳转
  console.log("", from);
  /*
  next() : 允许正常跳转
  1.路由导航守卫一定要跳转next(),如果不调用,路由无法跳转
  2.next() : 不加参数 通过检查  允许正常跳转
  3.next((path:'路径'))  : 检查不通过,进行拦截 跳转到指定的页面
  */
  // if (to.meta.isLogin) {
  //   //判断是否登录
  //   if (getToken()) {
  //     next()
  //     // next({
  //     //   path: '/login'
  //     // })
  //   } else {
  //     //未登录 跳转登录页
  //     next({
  //       path: '/login'
  //     })
  //   }
  // } else {
  //   next()
  // }
  // 代码优化
  if (to.meta.isLogin && !getToken()) {
    next({

      path: '/login'
    })
    setTimeout(() => {
      console.clear();
    }, 500)
  } else {
    next()
  }
})

export default router
